package com.exchange.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    public void set(String key, Object value, long timeout, TimeUnit timeUnit) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value, timeout, timeUnit);
    }
    
    public Object get(String key) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        return ops.get(key);
    }
    
    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }
    
    public void delete(String key) {
        redisTemplate.delete(key);
    }
    
    public void set(String key, Object value) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value);
    }
    
    public void expire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }
    
    // Cache exchange code validation results
    public void cacheExchangeCodeValidation(String code, Object result) {
        set("exchange_code:" + code, result, 300, TimeUnit.SECONDS); // Cache for 5 minutes
    }
    
    public Object getCachedExchangeCodeValidation(String code) {
        return get("exchange_code:" + code);
    }
    
    // Cache merchant dashboard data
    public void cacheMerchantDashboard(Long merchantId, Object data) {
        set("merchant_dashboard:" + merchantId, data, 600, TimeUnit.SECONDS); // Cache for 10 minutes
    }
    
    public Object getCachedMerchantDashboard(Long merchantId) {
        return get("merchant_dashboard:" + merchantId);
    }
    
    // Cache other frequently accessed data as needed
    public void cacheResourceLimits(Long merchantId, Object limits) {
        set("resource_limits:" + merchantId, limits, 3600, TimeUnit.SECONDS); // Cache for 1 hour
    }
    
    public Object getCachedResourceLimits(Long merchantId) {
        return get("resource_limits:" + merchantId);
    }
}